﻿document.write("<script language='javascript' src='/resources/js/views/showDataAndImage.js'></script>");
var action_report_analysis_area = "/report/analysis/area.do";
var host_path_action_report_query_depart_indicator="/report/query/depart/indicator.do";

var ttDepartIndicatorSelectCache= [];


function clearDepartIndicatorSelectCache() {
    ttDepartIndicatorSelectCache= [];
}
function loadDepartIndicator(level, curPage, pageSize) {
    loadDepartIndicatorByYear(level, curPage, pageSize, false);
}
// ttDepartIndicatorSelectCache 翻页的时候不能置为空
function loadDepartIndicatorByYear(level, curPage, pageSize, singleYear) {
    if(pageSize==null){
        pageSize=30;
    }
    if(curPage==null){
        curPage=1;
    }

    var yeares;
    if(singleYear){
        // 单个年份
        yeares = $("#year").combobox("getValue");//年份
    }else{
        yeares = $('#comboboxYear').combobox('getText');
    }

    var areaids="";
    if(level==3){
        areaids = $('#annualAnalysis_citySelect').combobox('getValues') + "";
    }else if(level==4){
        areaids = $('#countySelect').combobox('getValues') + "";
    }
    var departids = $('#ttDepartSelect').combobox('getValues') + "";
    var formsid = $('#formid').combobox('getValue');
    var iname = $('#iname').textbox('getValue');

    $.get(action_report_analysis_area,
    {"level": level, "areaid": areaids, "indicatorType": "-1", "years": yeares, "departid": departids, "iname": iname, "formsid": formsid, "page":curPage, "pageSize":pageSize}, function (json) {
        var code = json.code;
        if (code != 200) {
            $('#ttDepartIndicator').datagrid({data: []});
            $("#annualAnalysis_containerzhuzi").height("0px");
            $("#annualAnalysis_containerzhuzi").width("0px");
            return;
        }
        var data = json.data;
        var reportShowColumns = getDepartIndicatorShowColumns();
        $('#ttDepartIndicator').datagrid({
            fitColumns: true,
            frozen: true,
            columns: [
                reportShowColumns
            ],
            pagination:true,
            collapsible: true,
            singleSelect: false,// 是否单选
            checkOnSelect: true,//选中行后,checkbox选中
            selectOnCheck: true,//选中行后,checkbox选中
            data: data["results"],
            onSelect: function () {
                loadDepartIndicatorSelect();
            },
            onUnselect: function (rowIndex, rowData) {
                moveCache(rowData.id);
                loadDepartIndicatorSelect();
            },
            onSelectAll: function (rows) {
                loadDepartIndicatorSelect();
            },
            onUnselectAll: function () {
                loadDepartIndicatorSelect();
                ttDepartIndicatorSelectCache=[];
            }
        });

        var total=data.size;
        var dataLength=data.results.length;
        var totalPage = Math.ceil(total / pageSize);
        var start = (curPage-1) * pageSize;
        var pg = $("#ttDepartIndicator").datagrid("getPager");
        $(pg).pagination({
            total: total,
            pageList : [ 30, 500, 1000, 1500 ],
            pageSize: pageSize,
            pageNumber: curPage,
            beforePageText: '第',
            afterPageText: '页    共 ' + totalPage + ' 页',
            displayMsg: '当前显示 ' + (start + 1) + '-' + (start + dataLength) + ' 条记录 共 ' + total + ' 条记录',
            onSelectPage: function (curPage, pageSize) {
                loadDepartIndicator(level, curPage, pageSize)
            },
            onChangePageSize: function (ps) {
                pageSize = ps;
            }
        });
    }, 'json');
}

function loadDepartIndicatorSelect(){
    var row=$('#ttDepartIndicator').datagrid('getSelections');

    ttDepartIndicatorSelectCache = putCache(row);

    var reportShowColumns=[];
    reportShowColumns.push(defineTableReportAllColumns["iname"]); //指标名称
    reportShowColumns.push(defineTableReportAllColumns["code"]); //指标名称
    reportShowColumns.push(defineTableReportAllColumns["sname"]);//资料来源

    $('#ttDepartIndicatorSelect').datagrid( {
        data:ttDepartIndicatorSelectCache,
        fitColumns:true,
        columns: [
            reportShowColumns
        ]
    });
}

function getDepartIndicatorShowColumns() {
    var reportShowColumns = [];
    var ck = {
        title : '',
        field : 'ck',
        checkbox : true,
        width : 90
    };
    var departidShow = {
        title : 'departid',
        field : 'departid',
        hidden:true
    };
    reportShowColumns.push(ck);
    reportShowColumns.push(defineTableReportAllColumns["iname"]); //指标名称
    reportShowColumns.push(defineTableReportAllColumns["code"]); //指标名称
    // reportShowColumns.push(defineTableReportAllColumns["unit"]); //计量单位
    // reportShowColumns.push(defineTableReportAllColumns["places"]); //小数位数
    reportShowColumns.push(defineTableReportAllColumns["sname"]);//资料来源
    reportShowColumns.push(departidShow);//部门id

    return reportShowColumns;
}

function query(curPage, pageSize) {

    curPage = parseInt(curPage);
    pageSize = parseInt(pageSize);

    var yeares=$('#comboboxYear').combobox('getText');
    var yearList= [];
    if(yeares!=null ||yeares!='' || yeares!=undefined){
        yearList=yeares.split(',');
    }
    if(yearList.length>1){
        yearList.sort(funcSort);
    }
    var reportShowColumns = [];
    var ck = {
        title : '',
        field : 'ck',
        checkbox : true,
        width : 90
    };
    reportShowColumns.push(ck);
    reportShowColumns.push(defineTableReportAllColumns["iname"]);// 指标名称
    reportShowColumns.push(defineTableReportAllColumns["code"]);// 指标名称
    reportShowColumns.push(defineTableReportAllColumns["unit"]);// 计量单位
    reportShowColumns.push(defineTableReportAllColumns["places"]);//小数位数
    for (var i = 0; i < yearList.length; i++) {
        var c = {
            title : yearList[i],
            field : yearList[i],
            width : 90,
            align : "center",
            formatter : function(value, row, index) {
                // 数据上报的类型_每年的目标值_数值_显示数据展示时效果的规则_每年的备注
                var tempValue;
                if(value!=null && value.indexOf('_')!=-1){
                    tempValue = value.split('_')[2];
                }
                if(tempValue===null||tempValue==""||tempValue=="null"||tempValue=="NULL"){
                    return "";
                }else{
                    return tempValue;
                }
            }
        };
        reportShowColumns.push(c);// 年份
    }
    reportShowColumns.push(defineTableReportAllColumns["sname"]);// 资料来源

    var departids = getDepartidsFromCache();
    var formsid=$('#formid').combobox('getValue');
    var iname = $('#iname').textbox('getValue');
    var indicatores="";
    var rowindicatores=ttDepartIndicatorSelectCache;
    for (var i = 0; i < rowindicatores.length; i ++){
        indicatores+=rowindicatores[i]['indicator']+",";
    }
    if(indicatores.length>0){
        indicatores = indicatores.substring(0, indicatores.length - 1);
    }

    $.get(host_path_action_report_query_depart_indicator +
        '?years='+yeares+'&departids='+departids+'&indicatorids='+indicatores+
        '&iname='+iname+'&formsid='+formsid+'&page='+curPage+'&pageSize='+pageSize
        , function(json) {
        var code = json.code;
        if (code != 200) {
            $('#annualAnalysis_tt').datagrid({
                data : []
            });
            $("#annualAnalysis_containerzhuzi").height("0px");
            $("#annualAnalysis_containerzhuzi").width("0px");
            return;
        }
        var isShow;
        if (yearList.length == 0) {
            isShow = false;
        } else {
            isShow = true;
        }
        var data = json.data;
        var total = 0;
        if (data != null) {
            total = data.size;
        }
        var totalPage = Math.ceil(total / pageSize);
        var start = (curPage - 1) * pageSize;
        var dataLength = 0;
        data = data["results"];
        if (data != null) {
            dataLength = data.length;
        }
        $('#annualAnalysis_tt').datagrid({
            fitColumns : true,
            frozen : true,
            columns : [ reportShowColumns ],
            collapsible : true,
            checkOnSelect : true,// 选中行后,checkbox选中
            selectOnCheck : true,// 选中行后,checkbox选中
            singleSelect : false,// 是否单选
            loadMsg : '数据加载中,请稍后......',
            // 删除之后，不显示总数据数的排序号，只显示本页数的排序号
            pageNumber : curPage,// 显示数据列用
            pageSize : pageSize,
            pageList : [ 30, 500, 1000, 1500 ],
            rownumbers : isShow,
            // 删除之后，不显示总数据数的排序号，只显示本页数的排序号
            pagination : true,// 打开翻页功能
            striped : true,// 表格奇偶渐变色
            data : data,
            onSelect : function() {
                isCheck.push('check');
                // 显示页面效果
                $("#annualAnalysis_containerzhuzi").height("360px");
                $("#annualAnalysis_containerzhuzi").width($("#tabDiv").width()-40);
                show.tableshow();
                // showAnnualAnalysis();
                var row = $('#annualAnalysis_tt').datagrid('getSelections');
                if (row.length != 0) {
                    for (var i = 0; i < row.length; i++) {
                        row[i].iname = replaceStr(row[i].iname);
                    }
                    prepareShowData(row, false);
                }
            },
            onUnselect : function() {
                isCheck.splice(0, 1);
            },
            onSelectAll : function(rows) {
                for (var i = 0; i < rows.length; i++) {
                    isCheck.push('check');
                }
            },
            onUnselectAll : function() {
                isCheck.length = 0;
            }
        });

        var p = $('#annualAnalysis_tt').datagrid('getPager');
        $(p).pagination(
            {
                total : total,
                pageList : [ 30, 500, 1000, 1500 ],
                pageSize : pageSize,
                pageNumber : curPage,
                beforePageText : '第',
                afterPageText : '页    共 ' + totalPage + ' 页',
                displayMsg : '当前显示 ' + (start + 1) + '-'
                    + (start + dataLength) + ' 条记录 共 ' + total
                    + ' 条记录',
                onSelectPage : function(curPage, pageSize) {
                    query(curPage, pageSize);
                },
                onChangePageSize : function(ps) {
                    pageSize = ps;
                }
            });
    }, "json");
}

// function replaceNULL(value){
//     // return replace(new RegExp(value,"&nbsp;"))
//     console.log("value:"+value);
//     // value = value.replace(/&nbsp;/gi, "");
//     value = value.replace(/^\s+/g, "");
//     alert("de_value:"+value);
//     return value;
// }

function replaceStr(value){
    // console.log("value:"+value);
    return value.toString().replace(/&nbsp;/g, "");
    // var strValue = value.toString();
    // strValue = strValue.replace(/\*/g, "");
    // strValue = strValue.replace(/&nbsp;/g, "");
    // strValue = strValue.replace(/\s/g, "");
    // alert("replace:"+strValue);
    // var arr = [];
    // arr = strValue.split(",");
    // alert("arr:"+arr.length+":"+arr);
    // return arr;
}

var isShow = false;
function prepareShowData(data) {
    var datas = data;
    var yearCount = 0;

    var yeares=$('#comboboxYear').combobox('getText');
    var years= [];
    if(yeares!=null ||yeares!='' || yeares!=undefined){
        years=yeares.split(',');
    }
    if(years.length>1){
        years.sort(funcSort);
    }
    if (years != null && years != undefined) {
        yearCount = years.length;
    }
    var size = 0;
    if (datas != null) {
        size = datas.length;
    }
    zbname = [];
    series = [];
    jsonXData = [];
    conceal = {};
    // -------------------------------------------加绝对值指标---------------------------------------
    for (var i = 0; i < size; i++) {
        var aav = new Object();
        var aav2 = new Object(); // 加绝对值指标
        zbname.push(datas[i].iname);
        if (isTrue) { // 点击增长率出现
            zbname.push(datas[i].iname + '增长速度%');// 加绝对值指标
        }
        conceal[datas[i].iname + '增长速度%'] = false;
        aav.name = datas[i].iname;
        aav.type = 'bar';
        aav.barMaxWidth = 80;
        aav.label={normal: {show: true,position: 'top'}};
        var arr = [];
        aav2.name = datas[i].iname + '增长速度%';// 加绝对值指标
        aav2.type = 'line';// 加绝对值指标
        aav2.yAxisIndex = '1';
        aav2.label={normal: {show: true,position: 'top'}};
        var arr2 = [];// 加绝对值指标
        // 加绝对值指标---------------------------------------
        for (var j = 0; j < yearCount; j++) {
            if (datas[i][years[j]] != undefined) {
                if (j == 0) {
                    arr2.push(0);
                } else if (((datas[i][years[j]].split("_")[2] - datas[i][years[j - 1]].split("_")[2]) / datas[i][years[j - 1]].split("_")[2]) * 100 == Infinity) {
                    var avg = 0;
                    arr2.push(changeNum(avg));
                } else {
                    var avg = ((datas[i][years[j]].split("_")[2] - datas[i][years[j - 1]].split("_")[2]) / datas[i][years[j - 1]].split("_")[2]) * 100;
                    arr2.push(changeNum(avg));
                }
                arr.push(changeNum(datas[i][years[j]].split("_")[2]));
                jsonXData.push(years[j]);
            }
        }
        aav.data = arr;
        aav2.data = arr2;// 加绝对值指标
        series.push(aav);
        if (isTrue) {
            series.push(aav2); // 加绝对值指标
        }
    }

    if (data) {
        // 显示效果
        isShow = false;
        if (isTrue) {
            isShow = true;
        }
        showData(zbname, series, jsonXData, conceal, isShow);
    }
}

var show = {
    tableshow : function() {
        show.a = !show.a;
        if (show.a) {
            $("#annualAnalysis_chart").panel("expand", true);
        }
    },
    photoshow : function() {
        show.a = false;
    },
    chartshow : function() {
        show.a = true;
    }
};

function moveCache(aimId){
    var tempTtDepartIndicatorSelectCache =[];
    let j = 0;
    for (let i = 0; i < ttDepartIndicatorSelectCache.length; i++) {
        if(aimId != ttDepartIndicatorSelectCache[i].id){
            tempTtDepartIndicatorSelectCache[j] = ttDepartIndicatorSelectCache[i];
            j++;
        }
    }
    ttDepartIndicatorSelectCache = tempTtDepartIndicatorSelectCache;
}

function putCache(row){
    for (let i = 0; i < row.length; i++) {
        if(!imHere(row[i].id, ttDepartIndicatorSelectCache)){
            ttDepartIndicatorSelectCache[ttDepartIndicatorSelectCache.length]=row[i];
        }
    }
    return ttDepartIndicatorSelectCache;
}

function getDepartidsFromCache(){
    var departids="";
    for (let i = 0; i < ttDepartIndicatorSelectCache.length; i++) {
        departids+=ttDepartIndicatorSelectCache[i].departid+",";
    }
    return departids;
}

function imHere(idAim, row){
    for (let i = 0; i < row.length; i++) {
        if(idAim==row[i].id){
            return true;
        }
    }
    return false;
}


